#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include <strings.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>


enum
{
    USE_ERR,
    SOCKET_ERR,
    BIND_ERR,
};

void Useage(const std::string &str)
{
    std::cout << "Useage:\n\t" << str << " ip port \n";
    exit(USE_ERR);
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Useage(argv[0]);
    }
    std::string ip = argv[1];
    uint16_t port = std::stoi(argv[2]);

    srand(time(nullptr));

    int sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        std::cout << "socket create success\n";
        exit(SOCKET_ERR);
    }

    struct sockaddr_in server;
    bzero(&server, sizeof server);
    server.sin_family = AF_INET;
    server.sin_port = htons(port);
    server.sin_addr.s_addr = inet_addr(ip.c_str());

    std::string file("./");
    file += std::to_string(rand() % 100000);
    file += ".txt";
    std::cout << file << std::endl;
    pid_t id = fork();
    if (id == 0)
    {
        std::ofstream ofs(file.c_str(), std::ios::out);
        if(!ofs.is_open())
        {
            exit(1);
        }
        while (true)
        {
            // 3.接受结果
            char buff[1024];
            struct sockaddr_in peer;
            socklen_t len = sizeof peer;

            ssize_t n = ::recvfrom(sockfd, buff, sizeof(buff) - 1, 0, reinterpret_cast<struct sockaddr *>(&peer), &len);
            if (n > 0)
            {
                // 4.打印结果
                buff[n] = 0;
                ofs << buff << std::endl;
                // sleep(1);
            }
            else if (n == 0)
            {
                ofs << "server is quit, me too!!!\n";
                break;
            }
            else
            {
                ofs << "recv error\n";
                break;
                ;
            }
        }
    }
    while (true)
    {
        // 1. 获取输入
        std::string message;
        std::cout << "Please input# ";
        std::getline(std::cin, message);

        // 2.发送数据
        ssize_t n = ::sendto(sockfd, message.c_str(), message.size(), 0, reinterpret_cast<struct sockaddr *>(&server), sizeof server);
        if (n < 0)
        {
            std::cout << "send error\n";
            continue;
        }
    }

    return 0;
}
